package control;

import java.io.IOException;

import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import middlelayer.PacketBuffer;
import sniff.Sniff;
import sniff.pack.CommonPacket;
import ui.FuncPanel;

public class SystemControl {
	private static JpcapCaptor currentJpcapCaptor;
	private static int caplen = 1512;
	private static boolean promiscCheck = true;
	private static int time=50;
	public static final String lock = "stopSniff";
	public static boolean suspend = false;
	private static NetworkInterface currentDevice;
	private static Sniff currentSniff;
	private static Thread sniffThread;
	public static int speed = 500;
	public static int packNum=1; 
	public static void initSystem() {
		try {
			currentJpcapCaptor = JpcapCaptor.openDevice(getDeviceList()[0],caplen, promiscCheck, time);
			currentSniff = new Sniff(currentJpcapCaptor);
			sniffThread = new Thread(currentSniff);
			runSniff();
			stopSniff();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void runSniff() {
		sniffThread.start();
	}
	
	public static void startSniff() {
		setSuspend(false);
		SystemUIControl.setStartStopStatus(false);
	}
	public static void stopSniff() {
		setSuspend(true);
		SystemUIControl.setStartStopStatus(true);
	}
	
	public static void setJpcapCaptor(JpcapCaptor jp) {
		currentJpcapCaptor = jp;
	}
	
	public static NetworkInterface[] getDeviceList() {
		return JpcapCaptor.getDeviceList();
	}
	
	public static void appendPacket(CommonPacket comPack) {
		comPack.setNo(packNum++);
		PacketBuffer.appendToAllPackets(comPack);
		PacketBuffer.appendToShowPackets(comPack);
		SystemUIControl.appentOnePacketToShow(comPack);
	}
	
	private static void setSuspend(boolean suspend) {
        if (!suspend) {
            synchronized (lock) {
                lock.notifyAll();
            }
        }
        SystemControl.suspend = suspend;
    }
	public static boolean changeDevice(NetworkInterface device) {
		boolean b=false;
		if(device==null) {
			return false;
		}
		if(currentDevice==null) {
			currentDevice = device;
		}else if(!device.equals(currentDevice)){
			currentDevice = device;
		}else {
			return false;
		}
		try {
			stopSniff();
			currentJpcapCaptor = JpcapCaptor.openDevice(device,caplen, promiscCheck, time);
			currentSniff.setJpcap(currentJpcapCaptor);
			PacketBuffer.cleanAll();
			PacketBuffer.cleanShow();
			b=true;
		} catch (IOException e) {
			e.printStackTrace();
			b=false;
		}
		return b;
	}
	
}
